#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
语言检测器使用示例
"""

from language_detector import LanguageDetector

def basic_usage():
    """基本使用方法"""
    # 创建检测器实例
    detector = LanguageDetector()
    
    # 要检测的文本
    texts = [
        "这是一个中文句子",
        "This is an English sentence",
        "Это русский текст",
        "これは日本語です",
        "Ceci est français",
        "TMT 시그널 자유채팅방"
    ]
    
    print("=== 基本语言检测 ===")
    for text in texts:
        # 使用本地方法检测
        result = detector.detect_with_langdetect(text)
        
        if result['success']:
            print(f"文本: {text}")
            print(f"语言: {result['language']} ({result['language_name']})")
            print(f"置信度: {result['confidence']:.3f}")
            print("-" * 50)
        else:
            print(f"检测失败: {result['error']}")

def multiple_methods():
    """使用多种方法检测"""
    detector = LanguageDetector()
    
    text = "Hello, how are you today?"
    
    print("=== 多种方法检测同一文本 ===")
    print(f"文本: {text}\n")
    
    # 方法1: 简单规则检测
    result1 = detector.detect_with_simple_rules(text)
    print(f"简单规则: {result1['language']} ({result1['language_name']}) - 置信度: {result1['confidence']:.3f}")
    
    # 方法2: langdetect库
    result2 = detector.detect_with_langdetect(text)
    if result2['success']:
        print(f"langdetect: {result2['language']} ({result2['language_name']}) - 置信度: {result2['confidence']:.3f}")
    
    # 方法3: langid库
    result3 = detector.detect_with_langid(text)
    if result3['success']:
        print(f"langid: {result3['language']} ({result3['language_name']}) - 置信度: {result3['confidence']:.3f}")
    
    # 方法4: 免费在线API
    result4 = detector.detect_with_libre_translate(text)
    if result4['success']:
        print(f"LibreTranslate: {result4['language']} ({result4['language_name']}) - 置信度: {result4['confidence']:.3f}")

def best_result_detection():
    """获取最佳检测结果"""
    detector = LanguageDetector()
    
    text = "Bonjour, comment allez-vous?"
    
    print("=== 获取最佳检测结果 ===")
    print(f"文本: {text}\n")
    
    # 使用所有本地方法
    results = [
        detector.detect_with_simple_rules(text),
        detector.detect_with_langdetect(text),
        detector.detect_with_langid(text),
        detector.detect_with_libre_translate(text)
    ]
    
    # 显示所有结果
    print("所有方法的结果:")
    for result in results:
        if result['success']:
            print(f"  {result['method']:15}: {result['language']} ({result['language_name']}) - 置信度: {result['confidence']:.3f}")
        else:
            print(f"  {result['method']:15}: 失败 - {result['error']}")
    
    # 获取最佳结果
    best = detector.get_best_result(results)
    if best['success']:
        print(f"\n最佳结果: {best['language']} ({best['language_name']}) - 置信度: {best['confidence']:.3f}")

def telegram_data_detection():
    """检测Telegram数据"""
    detector = LanguageDetector()
    
    # 模拟Telegram群组数据
    telegram_groups = [
        {"t": "UPSI Shared Transport", "u": "prebetupsi", "s": 37431},
        {"t": "Чат для подписчиков Препода", "u": "prepodsteamchat", "s": 3819},
        {"t": "加密货币交流群", "u": "crypto_china", "s": 5234},
        {"t": "Bitcoin & Altcoins", "u": "bitcoin_alt", "s": 8765},
        {"t": "暗号資産情報交換", "u": "crypto_japan", "s": 2341}
    ]
    
    print("=== Telegram群组语言检测 ===")
    
    for group in telegram_groups:
        title = group['t']
        username = group['u']
        members = group['s']
        
        # 检测标题语言
        result = detector.detect_with_langdetect(title)
        
        print(f"群组: {title}")
        print(f"用户名: @{username}")
        print(f"成员数: {members:,}")
        
        if result['success']:
            print(f"检测语言: {result['language']} ({result['language_name']})")
            print(f"置信度: {result['confidence']:.3f}")
        else:
            print(f"检测失败: {result['error']}")
        
        print("-" * 60)

def batch_json_detection():
    """批量检测JSON文件中的数据"""
    import json
    import os
    
    detector = LanguageDetector()
    json_folder = "combot_data/json"
    
    if not os.path.exists(json_folder):
        print(f"JSON文件夹不存在: {json_folder}")
        return
    
    print("=== 批量检测JSON文件 ===")
    
    # 只处理前几个文件作为示例
    json_files = [f for f in os.listdir(json_folder) if f.endswith('.json')][:3]
    
    language_stats = {}
    
    for json_file in json_files:
        print(f"\n处理文件: {json_file}")
        
        json_path = os.path.join(json_folder, json_file)
        
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                groups = json.load(f)
            
            print(f"  群组数量: {len(groups)}")
            
            # 检测前5个群组的语言
            for i, group in enumerate(groups[:5]):
                title = group.get('t', '')
                if title:
                    result = detector.detect_with_langdetect(title)
                    if result['success']:
                        lang = result['language']
                        lang_name = result['language_name']
                        confidence = result['confidence']
                        
                        print(f"    {i+1}. {title[:30]}... -> {lang} ({lang_name}) [{confidence:.2f}]")
                        
                        # 统计语言分布
                        if lang not in language_stats:
                            language_stats[lang] = 0
                        language_stats[lang] += 1
                        
        except Exception as e:
            print(f"  处理文件出错: {e}")
    
    # 显示语言统计
    if language_stats:
        print(f"\n语言分布统计:")
        for lang, count in sorted(language_stats.items(), key=lambda x: x[1], reverse=True):
            lang_name = detector.language_names.get(lang, lang)
            print(f"  {lang_name} ({lang}): {count} 个群组")

def main():
    """主函数 - 演示所有功能"""
    print("🌍 语言检测器使用演示\n")
    
    # 1. 基本使用
    basic_usage()
    print("\n" + "="*60 + "\n")
    
    # 2. 多种方法比较
    multiple_methods()
    print("\n" + "="*60 + "\n")
    
    # 3. 最佳结果选择
    best_result_detection()
    print("\n" + "="*60 + "\n")
    
    # 4. Telegram数据检测
    telegram_data_detection()
    print("\n" + "="*60 + "\n")
    
    # 5. 批量JSON检测
    batch_json_detection()

if __name__ == "__main__":
    main()
